import React, { useState, useEffect } from "react";
import {Button, Input, Modal, Tag, Tooltip, Col, Row, message, Typography, Space, Divider} from "antd";
import IconCommon from "../../../common/IconCommon";
import { uuid } from "../../../common/utils/createId";
import { observer } from "mobx-react";
import md5 from "js-md5";
import IconBtn from "../../../common/iconBtn/IconBtn";
import copyMockUrl from "../../../common/copyLink";
import shareStore from "../store/ShareStore";
import { CopyOutlined, ShareAltOutlined, LockOutlined, GlobalOutlined } from '@ant-design/icons';

/**
 * 分享弹框组件
 * @param {Object} props - 组件属性
 * @param {string} props.targetId - 目标ID
 * @param {string} props.targetType - 目标类型 (workspace/category/api)
 * @param {string} props.targetName - 目标名称
 * @param {string} [props.name] - 显示文本（如果使用文本链接）
 * @param {boolean} [props.btn] - 是否显示为按钮
 * @param {boolean} [props.icon] - 是否显示为图标
 */
const CreateSingleShareModal = (props) => {
    const { targetId, targetType, targetName, name, btn, icon } = props;
    const { findShare, createShare, updateShare } = shareStore;

    const [code, setCode] = useState("");
    const [visibility, setVisibility] = useState(0);
    const [password, setPassword] = useState("");
    const [shareUrl, setShareUrl] = useState("");
    const [visible, setVisible] = useState(false);
    const [isCreated, setIsCreated] = useState(false);
    const [loading, setLoading] = useState(false);

    const workspaceId = localStorage.getItem("workspaceId");

    // 目标类型映射表
    const TARGET_TYPE_MAP = {
        workspace: "项目",
        category: "目录",
        api: "接口"
    };

    /**
     * 生成分享链接
     * @returns {string} 完整的分享URL
     */
    const generateShareUrl = (shareCode) => {
        return `${window.location.origin}/#/share/${shareCode}`;
    };

    /**
     * 展示分享弹框
     */
    const showModal = async () => {
        try {
            // 通过当前id进行md5，设置为分享的Id
            const generatedCode = md5(targetId);
            setCode(generatedCode);

            const res = await findShare(generatedCode);

            // 如果已存在分享，展示已有配置
            if (res.code === 0 && res.data) {
                const { visibility: existingVisibility, password: existingPassword } = res.data;
                setVisibility(existingVisibility);
                setPassword(existingPassword || "");
                setShareUrl(generateShareUrl(generatedCode));
                setIsCreated(true);
            } else {
                // 重置状态，准备新建分享
                setVisibility(0);
                setPassword("");
                setShareUrl("");
                setIsCreated(false);
            }

            setVisible(true);
        } catch (error) {
            message.error("分享初始化失败");
        }
    };

    /**
     * 创建新的分享
     */
    const handleCreateShare = async () => {
        try {
            setLoading(true);

            const param = {
                name: targetName,
                code: code,
                targetId,
                targetType,
                visibility,
                workspaceId,
                password: visibility === 1 ? password : null,
            };

            const res = await createShare(param);

            if (res && res.code === 0) {
                setShareUrl(generateShareUrl(code));
                setIsCreated(true);
                message.success("分享创建成功");
            } else {
                message.error("分享创建失败");
            }
        } catch (error) {
            message.error("分享创建失败");
        } finally {
            setLoading(false);
        }
    };

    /**
     * 更新分享可见性类型
     * @param {Event} e - 事件对象
     */
    const changeType = async (e) => {
        const type = e.target.value;
        setVisibility(type);

        // 如果是密码访问且未设置密码，生成新密码
        if (type === 1 && !password) {
            const newPassword = uuid(6);
            setPassword(newPassword);
        }

        // 如果已创建分享，则更新设置
        if (isCreated) {
            updateShareSettings(type);
        }
    };

    /**
     * 更新分享设置
     * @param {number} type - 可见性类型
     */
    const updateShareSettings = async (type) => {
        const param = {
            id: code,
            visibility: type,
            targetId,
            targetType
        };

        if (type === 1) {
            param.password = password || uuid(6);
        } else {
            param.password = "nullstring"; // 使用"nullstring"表示无密码
            setPassword("");
        }

        try {
            await updateShare(param);
        } catch (error) {
            message.error("更新分享类型失败");
        }
    };

    /**
     * 更新分享密码
     * @param {string} value - 新密码
     */
    const changePassword = async (value) => {
        if (!value.trim()) return;

        setPassword(value);

        // 只有在已创建分享的情况下才更新
        if (isCreated) {
            try {
                await updateShare({
                    id: code,
                    password: value,
                    targetType,
                    targetId,
                    visibility
                });
            } catch (error) {
                message.error("更新分享密码失败");
            }
        }
    };

    /**
     * 渲染不同类型的触发按钮
     */
    const renderTrigger = () => {
        if (name) {
            return <span className="link-text" onClick={showModal}>
                {name}
            </span>;
        }

        if (btn) {
            return (
                <IconBtn
                    className="pi-icon-btn-grey"
                    onClick={showModal}
                    name="分享"
                />
            );
        }

        if (icon) {
            return (
                <Tooltip placement="bottom" title="分享">
                  <span>
                    <IconCommon
                        icon="fenxiang"
                        style={{ margin: "5px 0 0 0", cursor: "pointer" }}
                        className="icon-s"
                        onClick={showModal}
                    />
                  </span>
                </Tooltip>
            );
        }

        return <a onClick={showModal} className={"display-flex-gap-5"}>
            <IconCommon
                icon="fenxiang"
                className="icon-s"
                onClick={showModal}
            />
            分享
        </a>;
    };

    /**
     * 渲染弹窗底部按钮
     */
    const renderFooter = () => {
        if (isCreated) {
            return null; // 创建成功后不显示底部按钮
        }

        return (
            <>
                <Button onClick={() => setVisible(false)}>取消</Button>
                <Button
                    type="primary"
                    onClick={handleCreateShare}
                    loading={loading}
                >
                    创建分享
                </Button>
            </>
        );
    };

    // 处理密码输入框点击事件
    const handlePasswordClick = (e) => {
        // 阻止事件冒泡到树的节点
        e.stopPropagation();
    };

    return (
        <>
            {renderTrigger()}
            <Modal
                destroyOnClose={true}
                title={
                    <Space>
                        <ShareAltOutlined />
                        <span>分享设置</span>
                    </Space>
                }
                open={visible}
                onCancel={() => setVisible(false)}
                centered
                footer={renderFooter()}
                width={580}
                className="share-modal-container"
            >
                <div className="share-modal-content">
                    <div className="share-info-section">
                        <Row align="middle" gutter={[16, 16]}>
                            <Col span={4}>
                                <Typography.Text type="secondary">名称</Typography.Text>
                            </Col>
                            <Col span={20}>
                                <Typography.Text strong>{targetName}</Typography.Text>
                            </Col>

                            <Col span={4}>
                                <Typography.Text type="secondary">类型</Typography.Text>
                            </Col>
                            <Col span={20}>
                                <Tag color="#1890ff" style={{ padding: '4px 8px' }}>
                                    {TARGET_TYPE_MAP[targetType] || targetType}
                                </Tag>
                            </Col>
                        </Row>
                    </div>

                    <Divider style={{ margin: '16px 0' }} />

                    <div className="share-settings-section">
                        <Row align="middle" gutter={[16, 16]}>
                            <Col span={4}>
                                <Typography.Text type="secondary">访问权限</Typography.Text>
                            </Col>
                            <Col span={20}>
                                <Space direction="vertical" style={{ width: '100%' }}>
                                    <div className="custom-radio-group">
                                        <div 
                                            className={`custom-radio-item ${visibility === 0 ? 'active' : ''}`}
                                            onClick={() => changeType({ target: { value: 0 } })}
                                        >
                                            <GlobalOutlined />
                                            <span>公开访问</span>
                                        </div>
                                        <div 
                                            className={`custom-radio-item ${visibility === 1 ? 'active' : ''}`}
                                            onClick={() => changeType({ target: { value: 1 } })}
                                        >
                                            <LockOutlined />
                                            <span>密码访问</span>
                                        </div>
                                    </div>
                                    {visibility === 1 && (
                                        <div onClick={handlePasswordClick} style={{ marginTop: 8 }}>
                                            <Input.Password
                                                style={{ width: "100%", maxWidth: "300px" }}
                                                value={password}
                                                onChange={(e) => setPassword(e.target.value)}
                                                onBlur={(e) => changePassword(e.target.value)}
                                                placeholder="请输入访问密码"
                                                prefix={<LockOutlined />}
                                            />
                                        </div>
                                    )}
                                </Space>
                            </Col>
                        </Row>
                    </div>

                    {isCreated && (
                        <>
                            <Divider style={{ margin: '16px 0' }} />
                            <div className="share-link-section">
                                <Row align="middle" gutter={[16, 16]}>
                                    <Col span={4}>
                                        <Typography.Text type="secondary">分享链接</Typography.Text>
                                    </Col>
                                    <Col span={16}>
                                        <div 
                                            className="share-modal-link" 
                                            id="share-link"
                                            style={{
                                                padding: '8px 12px',
                                                background: '#f5f5f5',
                                                borderRadius: '4px',
                                                wordBreak: 'break-all'
                                            }}
                                        >
                                            {shareUrl}
                                        </div>
                                    </Col>
                                    <Col span={4}>
                                        <Button
                                            type="primary"
                                            icon={<CopyOutlined />}
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                copyMockUrl("share-link");
                                            }}
                                        >
                                            复制
                                        </Button>
                                    </Col>
                                </Row>
                            </div>
                        </>
                    )}
                </div>
            </Modal>
            <style jsx>{`
                .share-modal-container {
                    .ant-modal-header {
                        padding: 16px 24px;
                        border-bottom: 1px solid #f0f0f0;
                    }
                    .ant-modal-body {
                        padding: 24px;
                    }
                }
                .share-modal-content {
                    .share-info-section, .share-settings-section, .share-link-section {
                        padding: 8px 0;
                    }
                }
                .share-modal-link {
                    font-family: monospace;
                    font-size: 14px;
                    line-height: 1.5;
                }
                .custom-radio-group {
                    display: flex;
                    gap: 8px;
                    .custom-radio-item {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        padding: 8px 16px;
                        border: 1px solid #d9d9d9;
                        border-radius: 4px;
                        cursor: pointer;
                        transition: all 0.3s;
                        background: #fff;
                        
                        &:hover {
                            border-color: #1890ff;
                            color: #1890ff;
                        }
                        
                        &.active {
                            background: #1890ff;
                            border-color: #1890ff;
                            color: #fff;
                            
                            .anticon {
                                color: #fff;
                            }
                        }
                        
                        .anticon {
                            font-size: 16px;
                        }
                    }
                }
            `}</style>
        </>
    );
};

export default observer(CreateSingleShareModal);